package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.R;
import com.ruan.common.Result;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.mapper.ToolBorrowRecordsMapper;
import com.ruan.pojo.*;
import com.ruan.pojoExt.ToolsExt;
import com.ruan.service.DepartmentService;
import com.ruan.service.EmployeeService;
import com.ruan.service.ToolBorrowRecordsService;
import com.ruan.service.ToolsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/tools")
public class ToolsController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private ToolsService toolsService;

    @Autowired
    private ToolBorrowRecordsService toolsBorrowRecordsService;

    @Autowired
    private ToolBorrowRecordsMapper toolBorrowRecordsMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;
    //工具信息分页查询, String name
    //创建一个controller方法，接收页面发送的请求并且接收参数（page,pageSize,name）
    @PostMapping("/selectAll/page/{page}/{pageSize}")
    public R<Page> page(@PathVariable int page,
                        @PathVariable int pageSize,
                        @RequestBody LTOQueryCondition LTOQueryCondition){//第三个参数 name 可能是从前端的用户输入或者页面的搜索框中获取的
        log.info("page = {},pageSize = {},LTOQueryCondition = {}"
                ,page,pageSize,LTOQueryCondition);
        //构造分页构造器             1     10
        Page<Tools> pageInfo = new Page<>(page,pageSize);
        Page<ToolsExt> toolsExtPage = new Page<>();//封装
        //构建条件构造器（动态封装传过来的过滤条件）
        // 通过定义泛型类型，一段代码可以用于不同的数据类型，使代码更加灵活和高效。
        LambdaQueryWrapper<Tools> queryWrapper = new LambdaQueryWrapper();
        //根据工具名搜索
        queryWrapper.like(!LTOQueryCondition.getName().equals(""),
                Tools::getTname,LTOQueryCondition.getName());
        //根据工具类型搜索
        queryWrapper.like(!LTOQueryCondition.getType().equals(""),
                Tools::getType,LTOQueryCondition.getType());
        //根据生产厂商搜索
        queryWrapper.like(!LTOQueryCondition.getMfrs().equals(""),
                Tools::getMfrs,LTOQueryCondition.getMfrs());
        //根据所属部门搜索
        queryWrapper.eq(LTOQueryCondition.getDepartmentId()!=null,
                Tools::getDepartmentId,LTOQueryCondition.getDepartmentId());

        toolsService.page(pageInfo,queryWrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询
        //条件构造器传进去之后，不需要去返回，因为把pageInfo传进去之后，在page内部，就会把查出来的数据进行封装，最终封装给page里的records,total。。

        BeanUtils.copyProperties(pageInfo,toolsExtPage,"records");//从pageInfo一个一个拷贝属性到employeeExtPage上(除了records)
        //处理
        List<Tools> records = pageInfo.getRecords();
        List<ToolsExt> list = records.stream().map((item) -> {//item:遍历出来的每一个项目对象
            ToolsExt toolsExt = new ToolsExt();//只有ToolsExt符合项目管理页面的要求，所以new一个出来,进行填充
            BeanUtils.copyProperties(item,toolsExt);//先填充入tools的普通属性
            Long departmentId = item.getDepartmentId();//拿到了每个员工所对应的部门id
            Department department = departmentService.getById(departmentId);

            if(department != null){//能查到工具所属的部门
                String departmentName = department.getName();
                toolsExt.setDepartmentName(departmentName);//填充入employee没有的employeeName属性
            }
//            toolsExt.setCreatedUser(createdUser.getName());
//            toolsExt.setUpdatedUser(updatedUser.getName());
            return toolsExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
        }).collect(Collectors.toList());//就转成集合了，赋给List<departmentExt> list
//        System.out.println("list里有了什么"+list);//.toString()
        toolsExtPage.setRecords(list);//list获得了改造过后的departmentExt集合之后，被用来设置page对象的Records属性

        return R.success(toolsExtPage);
//        return new Result(Code.SELECT_OK,toolsExtPage);
    }

    @GetMapping("/exportToExcel")
    public ResponseEntity<byte[]> exportToExcel(){
        try {
            byte[] excelBytes = toolsService.exportToExcel();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setContentDispositionFormData("attachment", "工具表.xlsx");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @DeleteMapping("/deleteTool/{id}")
    public Result deleteTool(@PathVariable Integer id){
        try {
            return toolsService.deleteTools(id);
//            return new Result(Code.DELETE_OK,"删除工具成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.DELETE_ERR,"工具信息删除失败！");
        }
    }

    @GetMapping("/selectAllTools")
    public R<List<Tools>> getAllTools(){
        log.info("查询所有的工具id和name和库存");
        // 从数据库中检索所有工具名字
        LambdaQueryWrapper<Tools> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Tools::getId,Tools::getTname,Tools::getTotal,Tools::getPrice);
        List<Tools> toolsList = toolsService.list(queryWrapper);
//        System.out.println("工具有"+toolsList);
        if(toolsList!=null){
            return R.success(toolsList);
        }
        return R.error("仓库为空");
    }

      @GetMapping("/getType")
      public R<List<String>> getAllToolsType(){
          log.info("查询所有的工具类型");
          // 从数据库中检索所有员工名字
          LambdaQueryWrapper<Tools> queryWrapper = new LambdaQueryWrapper<>();
          queryWrapper.select(Tools::getType);
          List<Tools> toolsTypeList = toolsService.list(queryWrapper);
      //让工具类型每种都独一无二
          List<String> toolsType = toolsTypeList.stream()
                  .map(Tools::getType) // 获取所有工具类型
                  .distinct() // 去除重复的工具类型
                  .collect(Collectors.toList()); // 转换为列表

//          System.out.println("工具类型有"+toolsType);
          if(toolsType!=null){
              return R.success(toolsType);
          }
          return R.error("工具类型为空");
      }

    //新增工具
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Tools tools){
        log.info("新增工具，工具信息：{}",tools.toString());
        toolsService.save(tools);//把这个对象存进去
//save方法继承自mybatis-plus的父接口IService（看看application.yml文件）,可以直接调用
        return R.success("新增工具信息成功");
    }

    @PostMapping("/updateTool")
    public Result updateTool(@RequestBody Tools tool){
        if (toolsService.updateById(tool)){
            return new Result(Code.UPDATE_OK,"工具信息修改成功！");
        }
        return new Result(Code.UPDATE_ERR,"工具信息修改失败！");
    }

    @PutMapping("/updateTotal/{id}")
    public Result updateTotal(@PathVariable Long id, @RequestBody Map<String, Integer> total) {
        try {
            Tools tool = toolsService.getById(id);
            tool.setTotal(total.get("total"));
            toolsService.updateById(tool);
            return new Result(Code.UPDATE_OK,"工具库存修改成功！");
        } catch (Exception e) {
            return new Result(Code.UPDATE_ERR,"工具库存修改失败！");
        }
    }


}
